import os
import time
import pytesseract
import keyboard
try:
    from PIL import Image
except ImportError:
    import Image
import pyautogui
import serial
import serial.tools.list_ports
# import cv2



# 获取所有串口设备实例。
# 如果没找到串口设备，则输出：“无串口设备。”
# 如果找到串口设备，则依次输出每个设备对应的串口号和描述信息。
ports_list = list(serial.tools.list_ports.comports())
if len(ports_list) <= 0:
    print("无串口设备。")
else:
    print("可用的串口设备如下：")
    for comport in ports_list:
        print(list(comport)[0], list(comport)[1])

# # 打开 COM17，将波特率配置为115200，数据位为7，停止位为2，无校验位，读超时时间为0.5秒。
# ser = serial.Serial(port="COM17",
#                     baudrate=115200,
#                     bytesize=serial.SEVENBITS,
#                     parity=serial.PARITY_NONE,
#                     stopbits=serial.STOPBITS_TWO,
#                     timeout=0.5)
ser = serial.Serial("COM4", 9600)  # 打开COM17，将波特率配置为115200，其余参数使用默认值
if ser.isOpen():  # 判断串口是否成功打开
    print("打开串口成功。")
    print(ser.name)  # 输出串口号
else:
    print("打开串口失败。")

# print(pytesseract.get_languages(config='')) # 列出支持的语言
# print(pytesseract.image_to_string(Image.open('test.png'), lang='chi_sim+eng'))
print("按ALT选择位置")
keyboard.wait('ALT')
x0, y0 = pyautogui.position()  # 返回鼠标的坐标
print("起始位置：" + str(x0) + "," + str(y0))
keyboard.wait('ALT')
x1, y1 = pyautogui.position()  # 返回鼠标的坐标
print("结束位置：" + str(x1) + "," + str(y1))
area = [x0, y0, x1 - x0 + 1, y1 - y0 + 1]
print(area)

a = 0
start = time.perf_counter()
while a<100:
    img = pyautogui.screenshot(region=area)  # x,y,w,h
    #img.save('screenshot.png')
    # img = Image.open('test.png')
    # config = r'--oem 3 --psm 6 outputbase digits'  #
    config = r'-c tessedit_char_whitelist=0123456789 --psm 6'  # 使用白名单 仅数字
    osd = pytesseract.image_to_string(img, config=config)
    print(osd)
    write_len = ser.write(osd.encode('utf-8'))
    print("串口发出{}个字节。".format(write_len))
    a += 1
end = time.perf_counter()
print("ls", end-start)
ser.close()


def position():
    try:
        screenWidth, screenHeight = pyautogui.size()
        x, y = pyautogui.position()  # 返回鼠标的坐标
        print('屏幕尺寸: (%s %s),  鼠标坐标 : (%s, %s)' % (screenWidth, screenHeight, x, y))
    except KeyboardInterrupt:
        print('结束')
